/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { isEmpty } from 'lodash';
import isEqual from 'react-fast-compare';
import { Drawer, Table } from 'antd';
import { Button, Intent, Position, Tooltip } from '@blueprintjs/core';
import TruncateString from 'react-truncate-string';

// DnD Selections
import SelectMembers from './SelectMembers';

// Styles
import './SelectLevels.css';

// Constants
const { Column } = Table;

class SelectLevels extends Component {
  state = {
    hierarchyGroup: {},
    selectedLevel: '',
    isShowSelectMembers: false
  };

  shouldComponentUpdate(nextProps, nextState) {
    return (
      this.props.title !== nextProps.title ||
      !isEqual(this.props.hierarchyGroup, nextProps.hierarchyGroup) ||
      !isEqual(this.props.levels, nextProps.levels) ||
      this.props.visible !== nextProps.visible ||
      this.state.selectedLevel !== nextState.selectedLevel ||
      this.state.isShowSelectMembers !== nextState.isShowSelectMembers
    );
  }

  hasMembersSelected(hierarchy, level) {
    if (
      hierarchy &&
      hierarchy.levels &&
      hierarchy.levels.hasOwnProperty(level) &&
      hierarchy.levels[level].hasOwnProperty('selection') &&
      hierarchy.levels[level].selection.hasOwnProperty('members') &&
      !isEmpty(hierarchy.levels[level].selection.members)
    ) {
      return true;
    }

    return false;
  }

  handleShowSelectMembers(level) {
    this.setState({
      selectedLevel: level,
      isShowSelectMembers: true
    });
  }

  handleRemoveLevel(levelIndex) {
    const { levels, removeLevel } = this.props;
    const levelName = levels[levelIndex]['level'];

    removeLevel(levelIndex, levelName);
  }

  handleCloseSelectMembers = () => {
    this.setState({
      // selectedLevel: '',
      isShowSelectMembers: false
    });
  };

  render() {
    const {
      title,
      hierarchyGroup,
      levels,
      visible,
      setMembers,
      onClose
    } = this.props;
    const { selectedLevel, isShowSelectMembers } = this.state;

    return (
      <Drawer
        className="sku-select-levels"
        title={<TruncateString text={title} />}
        width={320}
        onClose={onClose}
        visible={visible}
        zIndex={2000}
      >
        <Table
          className="sku-table-levels"
          dataSource={levels}
          pagination={false}
          showHeader={false}
          size="middle"
          title={() => <b>Levels:</b>}
        >
          <Column
            className="sku-column-levels"
            title="Levels"
            dataIndex="level"
            key="level"
            render={(text, record) => (
              <TruncateString
                text={record.level}
                style={{
                  fontWeight: this.hasMembersSelected(
                    hierarchyGroup.hierarchy,
                    record.level
                  )
                    ? 'bold'
                    : 'normal'
                }}
              />
            )}
          />
          <Column
            title="Action"
            align="right"
            key="action"
            render={(text, record) => (
              <Fragment>
                <Tooltip
                  content={<span>Select Members</span>}
                  position={Position.TOP}
                >
                  <Button
                    icon="plus"
                    intent={Intent.PRIMARY}
                    onClick={this.handleShowSelectMembers.bind(
                      this,
                      record.level
                    )}
                    minimal
                  />
                </Tooltip>
                <Tooltip
                  content={<span>Remove Level</span>}
                  position={Position.TOP}
                >
                  <Button
                    icon="minus"
                    intent={Intent.DANGER}
                    onClick={this.handleRemoveLevel.bind(this, record.key)}
                    minimal
                  />
                </Tooltip>
              </Fragment>
            )}
          />
        </Table>
        <div
          style={{
            position: 'absolute',
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e8e8e8',
            padding: '10px 16px',
            left: 0,
            background: '#fff'
          }}
        >
          <Button text="Close" onClick={onClose} />
        </div>

        {isShowSelectMembers && (
          <SelectMembers
            hierarchyGroup={hierarchyGroup}
            level={selectedLevel}
            visible={isShowSelectMembers}
            setMembers={setMembers}
            onClose={this.handleCloseSelectMembers}
          />
        )}
      </Drawer>
    );
  }
}

SelectLevels.propTypes = {
  title: PropTypes.string,
  hierarchyGroup: PropTypes.object.isRequired,
  levels: PropTypes.array.isRequired,
  visible: PropTypes.bool.isRequired,
  removeLevel: PropTypes.func.isRequired,
  setMembers: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired
};

export default SelectLevels;
